<?php

namespace Virchow\VirlumenTelescopeDashboard\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use Virchow\VirlumenTelescopeDashboard\Contracts\EntriesRepository;
use Virchow\VirlumenTelescopeDashboard\Storage\EntryQueryOptions;

abstract class EntryController extends Controller
{
    /**
     * The entry type for the controller.
     *
     * @return string
     */
    abstract protected function entryType();

    /**
     * The watcher class for the controller.
     *
     * @return string
     */
    abstract protected function watcher();

    protected $storage;

    protected function setProjectConnection(){
        $projectId = request('projectId',0);
        $projectInfo = \App\Models\Project::query()->find($projectId);
        if($projectInfo){
            \Illuminate\Support\Facades\Config::set('database.connections.project_'.$projectId , [
                'driver' => $projectInfo['db_connection'],
                'url' => '',
                'host' => $projectInfo['db_host'],
                'port' => $projectInfo['db_port'],
                'database' => $projectInfo['db_database'],
                'username' => $projectInfo['db_username'],
                'password' => $projectInfo['db_password'],
                'unix_socket' => env('DB_SOCKET', ''),
                'charset' => 'utf8mb4',
                'collation' => 'utf8mb4_unicode_ci',
                'prefix' => $projectInfo['db_prefix'],
                'prefix_indexes' => true,
                'strict' => true,
                'engine' => null
            ]);
            $connection = 'project_'.$projectId;
        }else{
            $connection = config('telescope.storage.database.connection');
        }
        $this->storage = new \Virchow\VirlumenTelescopeDashboard\Storage\DatabaseEntriesRepository($connection);
    }

    /**
     * List the entries of the given type.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Laravel\Telescope\Contracts\EntriesRepository  $storage
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $this->setProjectConnection();
        return response()->json([
            'entries' => $this->storage->get(
                $this->entryType(),
                EntryQueryOptions::fromRequest($request)
            ),
            'status' => $this->status(),
        ]);
    }

    /**
     * Get an entry with the given ID.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function show()
    {
        $id = request('telescopeEntryId',0);
        $this->setProjectConnection();
        $entry = $this->storage->find($id)->generateAvatar();
        return response()->json([
            'entry' => $entry,
            'batch' => $this->storage->get(null, EntryQueryOptions::forBatchId($entry->batchId)->limit(-1)),
        ]);
    }

    /**
     * Determine the watcher recording status.
     *
     * @return string
     */
    protected function status()
    {
        if (! config('telescope.enabled', false)) {
            return 'disabled';
        }

        if (cache('telescope:pause-recording', false)) {
            return 'paused';
        }

        $watcher = config('telescope.watchers.'.$this->watcher());

        if (! $watcher || (isset($watcher['enabled']) && ! $watcher['enabled'])) {
            return 'off';
        }

        return 'enabled';
    }
}
